import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    cookie_cart = request.COOKIES.get('carts')

    if not cookie_cart:
        return response

    cookie_cart = pickle.loads(base64.b64decode(cookie_cart.encode()))

    new_dict = {}
    new_add = []
    new_remove = []

    for sku_id, item in cookie_cart.items():

        new_dict[sku_id] = item['count']

        if item['selected']:
            new_add.append(sku_id)
        else:
            new_remove.append(sku_id)

    redis_conn = get_redis_connection('carts')

    pl = redis_conn.pipeline()
    pl.hmset('carts_%s' % user.id, new_dict)

    if new_add:
        pl.sadd('selected_%s' % user.id, *new_add)
    if new_remove:
        pl.srem('selected_%s' % user.id, *new_remove)
    pl.execute()

    response.delete_cookie('carts')

    return response
